<?php

//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                              |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: anguolei@clcw.com.cn                                           |
// +------------------------------------------------------------------------+
//
/**
 * 回车
 */

namespace AuctionBack\Controller;

use AuctionCore\AuctionOrder\AuOrder;
use AuctionCore\CarResource\Car;
use AuctionCore\Cashier\Payment;
use AuctionCore\Common\AjaxPage;
use AuctionCore\CarResource\BreachCar;
use AuctionCore\Fours\Fours;
use AuctionCore\PurchaseOrder\PurchaseOrder;
use Think\Log;
use AuctionCore\CarOwner\Owner;
use AuctionCore\Other\Store;
use AuctionCore\Cashier\Collection;
use AuctionCore\CarOwner\OwnerList as OwnerList;
use AuctionCore\ChangeOrder\ChangeOrder;
use AuctionCore\AuctionOrder\Signature;
use AuctionCore\CarResource\CarSource;
use AuctionBack\Logic\RefundLogic;
use AuctionBack\Logic\CarReportLogic;


class BreachCarController extends BaseController
{
    public function __construct()
    {
        parent::__construct();
        $this->emp_id = $this->user_info['emp_id'];
    }

    //待复检
    public function index()
    {
        $this->display();
    }

    //违约车辆列表
    public function breach_car_list()
    {
        $page = I("get.p/d", 1);
        $limit = 10;
        $status = I('get.status', 0);
        $pay_status = I('get.pay_status/d', 0);
        $location_area = I('get.location_area', 0);
        if (!$location_area) {
            $location_area = $this->user_info['bc_code'];
        } else {
            $location_area = [$location_area];
        }
        $sno = I("get.sno", '');
        $seller_name = I('get.seller_name');
        $seller_phone = I('get.seller_phone');
        $params = [
            'status' => $status,
            'pay_status' => $pay_status,
            'location_area' => $location_area,
            'sno' => $sno,
            'seller_name' => $seller_name,
            'seller_phone' => $seller_phone
        ];
        $result = BreachCar::get_list($page, $limit, $params);
        $total = $result['total'] > 0 ? $result['total'] : 0;
        $list = $result['list'] > 0 ? $result['list'] : [];
        $Page = new AjaxPage($total, $limit, "get_page");
        $Page->setConfig('theme', " %totalRow% %header% %nowPage%/%totalPage% 页 %first% %upPage% %prePage% %linkPage% %downPage% %nextPage% %end% %jumpform%");
        $page_show = $Page->show();

        $this->assign('p', $page);
        $this->assign('page', $page_show);
        $this->assign('list', $list);
        $this->assign('status', $status);
        $this->display();
    }

    //待检测列表
    public function waiting_check_list()
    {
        $page = I("get.p", 1);
        $size = 10;
        $params = array();
        $params['status'] = 'waiting';
        $params['pay_status'] = I('get.pay_status/d', 0);
        $params['trace_type'] = -1;
        $params['location_area'] = I('get.location_area');
        if (!$params['location_area']) {
            $params['location_area'] = !$this->is_hq ? array_flip($this->bc_city) : array();
        }
        $params['sno'] = I("get.sno", '');

        //$params['tab'] = 1;

        //获取list
        $ol = new OwnerList();
        $result = $ol->getWaitingCheckList($page, $size, $params);
        $Page = new \AuctionCore\Common\AjaxPage($result['total'], $size, "get_page");
        $Page->setConfig('theme', " %totalRow% %header% %nowPage%/%totalPage% 页 %first% %upPage% %prePage% %linkPage% %downPage% %nextPage% %end% %jumpform%");
        $show = $Page->show(); // 分页显示输出
        $this->assign('page', $show); // 赋值分页输出
        $this->assign('list', $result['list']);
        $this->assign("business_status", C("BUSINESS_STATUS"));
        $this->assign('channel_type', C("CHANNEL_TYPE"));
        $this->assign("params", $params);
        $this->display();
    }

    //车辆信息
    public function breach_car_info()
    {
        $car_id = I('get.car_id/d', 0);
        $bc_id = I('get.bc_id/d', 0);
        if ($car_id < 1) {
            $this->helpJsRedirect("参数不正确");
        }
        $bc = new BreachCar($car_id);
        $detail = $bc->breach_car_info($bc_id);
        //die;
        if ($detail['status'] == 2) {
            //echo $detail['order_id'];die();
            $orderObj = new AuOrder($detail['order_id']);
            $order = $orderObj->detail();
            $detail['bidding_end_time'] = $order['bidding_end_time'];
            $detail['highest_price'] = $order['bid_best_price'] > $order['bidding_best_price'] ? $order['bid_best_price'] : $order['bidding_best_price'];
            $detail['reserve_price'] = $order['reserve_price'];
            $detail['is_consult'] = $order['is_consult'];
            $detail['company_subsidies'] = $order['company_subsidies'];
        }
        $this->assign('detail', $detail);
        $location_area_code = $detail['location_area_code']; //车辆所在地城市编号

        $map = array();
        $map['status'] = array('eq', 0);
        $map['type'] = 3; //交付店
        $map['city'] = ['in', $location_area_code]; //只能显示车辆所在地的门店

        $store = new \AuctionCore\Other\Store();
        $stores = $store->get_stores($map); //得到门店

        //打款帐号
        $fours = new Fours();
        $fours_detail = $fours->get_fours_info(['channel_id' => $detail['channel_id']]);
        $fours_bank_account = $fours->get_bank_account_list_by_fid($fours_detail['fid']);
        $fours_bank_account_total = count($fours_bank_account);

        $car = new Car($car_id);
        $carDetail = $car->detail();
        $sid = $carDetail['sid'];
        $firstPaymentData = $this->getFirstPayment($sid);
        $collectionPaymentData = $this->getCollectionPaymentInfo($detail);
        $changeOrderData = $this->getModifyOrder($detail['mid']); //获取变更单信息

        $this->assign('change_order_data', $changeOrderData); //变跟单信息
        $this->assign('collection_payment_data', $collectionPaymentData); //首付款信息
        $this->assign('first_payment_data', $firstPaymentData); //首付款信息
        $this->assign('stores', $stores);
        $this->assign('fours_bank_account', $fours_bank_account);
        $this->assign('fours_bank_account_total', $fours_bank_account_total);
        $this->display();
    }


    /**
     * 得到首付款信息
     *
     * @param $sid 车源编号
     * @return array|mixed
     */
    public function getFirstPayment($sid)
    {
        $purchaseOrderObj = new PurchaseOrder();
        $purchaseOrderData = $purchaseOrderObj->viewBySid($sid);
        if (empty($purchaseOrderData)) {
            return [];
        }
        $purchaseOrderId = $purchaseOrderData['id']; //采购单编号
        $paymentRelation = $purchaseOrderObj->getPaymentAndPurchaseOrderRelation($purchaseOrderId, [1, 2]);
        $paymentId = $paymentRelation['payment_id'];
        $paymentObj = new Payment($paymentId);
        $paymentData = $paymentObj->getInfo();
        if ($paymentData['status'] != 1) { //如果不是已付款，就让付款金额变为0
            $paymentData['amount'] = 0;
        }
        return $paymentData;
    }

    /**
     * 得到收付款信息
     *
     * @param array $breachDetail 违约信息数据
     * @return array
     */
    public function getCollectionPaymentInfo($breachDetail)
    {
        $data = [];
        $collectionId = $breachDetail['collection_id'];
        $collectionCarId = $breachDetail['collection_id_car'];
        $paymentId = $breachDetail['payment_id'];

        if ($collectionId > 0) { //车主赔付
            $collectionObj = new Collection($collectionId);
            $data['collectionData'] = $collectionObj->getInfo();
            /*if($collectionData['status'] != 1){ //如果未付款，设置收款金额为0
                $collectionData['amount'] = 0;
            }*/
        }

        if ($collectionCarId > 0) { //应收车款
            $collectionObj = new Collection($collectionCarId);
            $data['collectionCarData'] = $collectionObj->getInfo();
        }

        if (!empty($paymentId)) {
            $paymentObj = new Payment($paymentId);
            $data['paymentData'] = $paymentObj->getInfo();
            /*if($paymentData['status'] != 1){ //如果未付款，设置收款金额为0
                $paymentData['amount'] = 0;
            }*/
        }
        return $data;
    }

    public function getModifyOrder($mid)
    {
        $changeOrderObj = new ChangeOrder($mid);
        $data = $changeOrderObj->detail();
        $data['modify_reason'] = C('MODIFY_REASON.' . $data['modify_reason']);
        $data['status'] = C('MODIFY_STATUS.' . $data['status']);
        return $data;
    }

    // 重拍
    public function re_auction()
    {
        $order_id = I('post.order_id/d', 0);
        $car_id = I('post.car_id/d', 0);
        $bc_id = I('post.bc_id/d', 0);
        $is_re_check = I('post.is_re_check/d', 0);

        if ($car_id < 1) {
            $this->helpJsonResult(400, "参数错误");
        }
        if ($bc_id < 1) {
            $this->helpJsonResult(400, "参数错误");
        }
        $bc = new BreachCar($car_id);
        $bc_info = $bc->iss_detail($bc_id);

        if (empty($bc_info)) {
            $this->helpJsonResult(400, "未查询到违约车辆信息");
        }
        $reserve_price = I('post.reserve_price');
        if ($reserve_price <= 0) {
            $this->helpJsonResult(400, "请输入正确的保留价");
        }
        $remark = I('post.remark');
        $now = date("Y-m-d H:i:s");
        $car = new Car($car_id);
        $car_detail = $car->detail();
        M()->startTrans();

        if ($is_re_check) {   //如果是重新检测的话。操作三步：1.车主信息表中，插入一条记录，状态标注为待检测
            // 2.自收车辆状态修改为已重拍
            //  3.车辆状态更新为10，待检测.违约状态修改成 违约
            $result = $this->addCarOwner($car);

            $result1 = $car->update([
                'car_status' => 10,
                'reserve_price' => $reserve_price,
                'is_dealer_breach' => 1,
                'is_re_check' => 1,
                'modify_time' => date('Y-m-d H:i:s', time()),
            ]);

            $result2 = $bc->update([
                'status' => 1,
                'reserve_price' => $reserve_price,
                'remark' => $remark,
                'emp_id' => $this->emp_id,
                'emp_name' => $this->user_info['real_name'],
                'deal_time' => $now,
                'report_type' => 1, //报告处理方式 重新检测
            ], $bc_id);

            if (!$result || $result1 === false || $result2 === false) {
                M()->rollback();
                $this->helpJsonResult(500, "操作失败");
            }

            $this->log_record($car_id, $order_id, '违约车辆重新检测，进入检测调度');
        } else {
            $rs = $bc->update([
                'status' => 1,
                'reserve_price' => $reserve_price,
                'remark' => $remark,
                'emp_id' => $this->emp_id,
                'emp_name' => $this->user_info['real_name'],
                'deal_time' => $now
            ], $bc_id);

            $rs1 = $car->update([
                'car_status' => 7, //待重拍
                're_auction_type' => 2,
                're_auction_reason' => $remark,//重拍原因
                'reserve_price' => $reserve_price,
                'is_dealer_breach' => 1
            ]);

            if (!$rs || !$rs1) {
                M()->rollback();
                $this->helpJsonResult(500, "操作失败");
            }
            $this->log_record($car_id, $order_id, '违约车辆，重拍');
        }


        $unLockResult = $this->unLockAll($car);
        if (!$unLockResult) {
            M()->rollback();
            $this->helpJsonResult(500, "解锁采购单失败");
        }

        //更改车源状态
        // $carInfo = $car ->detail();
        // $CarSource = new CarSource($carInfo['sid']);
        // $csData = [];
        // $csData['status'] = 100;
        // $res_cs = $CarSource->update($csData);

        M()->commit();
        $this->helpJsonResult(200, '操作成功');
    }


    /**
     * 解锁采购单，及付款单
     *
     * @param object $carObj 车源对象
     * @return bool
     */
    public function unLockAll($carObj)
    {
        $carData = $carObj->detail();
        $sid = $carData['sid'];

        $purchaseOrderObj = new PurchaseOrder();
        $purchaseOrderData = $purchaseOrderObj->viewBySid($sid);
        $purchaseOrderId = $purchaseOrderData['id']; //采购单编号

        ///采购单解锁
        $po = new PurchaseOrder($purchaseOrderId);
        $res_purchase_order = $po->unLockById();

        //付款单解锁(采购单)
        $carSource = $carData['car_source'];
        if ($carSource == 1) { //如果是4s店车源，那么付款单类型是 1 1 => '采购应付',
            $payType = 1;
        }
        if ($carSource == 2) { //如果是个人车源，那么付款单类型是 2 	2 => '采购应付（首）',
            $payType = 2;
        }
        $payment_id = $po->getPaymentIdByPoid($payType);//根据采购单编号和付款单类型，找到相应的付款单
        $res_payment = true;
        if ($payment_id) {
            $res_payment = Payment::unlock($payment_id);
        }
        if ($res_purchase_order && $res_payment) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 添加车主信息
     *
     * @param object $car 车对象
     * @return int
     */
    public function addCarOwner($car)
    {
        $reserveTime = I('post.reserve_time'); //检测预约时间
        $reserveStoreId = I('post.reserve_store'); // 检测预约门店
        $remark = I('post.remark');
        $store = new Store();
        $storeData = $store->detail(['store_id' => $reserveStoreId]);

        $carDetail = $car->detail();

        $ownerId = $carDetail['owner_id'];
        $carOwnerObj = new Owner($ownerId);
        $carOwner = $carOwnerObj->detail();

        $carOwnerData['business_status'] = 4;
        $carOwnerData['is_assigned'] = 0;
        $carOwnerData['reserve_time'] = transform_date($reserveTime, 2); //预约时间
        $carOwnerData['reserve_store'] = $reserveStoreId; // 预约门店
        $carOwnerData['service_method'] = 3;
        $carOwnerData['reserve_remark'] = $remark; //检测预约备注
        $carOwnerData['uid'] = $carOwner['uid'];
        $carOwnerData['province'] = $storeData['province'];
        $carOwnerData['city'] = $storeData['city'];
        $carOwnerData['area'] = $storeData['area'];
        $carOwnerData['seller_name'] = $carOwner['seller_name'];
        $carOwnerData['phone'] = $carOwner['phone'];
        $carOwnerData['car_model'] = $carOwner['car_model'];
        $carOwnerData['brand_id'] = $carOwner['brand_id'];
        $carOwnerData['series_id'] = $carOwner['series_id'];
        $carOwnerData['model_id'] = $carOwner['model_id'];
        $carOwnerData['mileage'] = $carOwner['mileage'];
        $carOwnerData['isou_id'] = $carOwner['isou_id'];
        $carOwnerData['comefrom'] = $carOwner['comefrom'];
        $carOwnerData['comefrom_url'] = $carOwner['comefrom_url'];
        $carOwnerData['posttime'] = date('Y-m-d H:i:s', time());
        $carOwnerData['first_reg_date'] = $carDetail['first_reg_date'];
        $carOwnerData['location_area'] = $carOwner['location_area'];
        $carOwnerData['old_car_id'] = $carDetail['car_id'];
        $carOwnerData['modify_time'] = date('Y-m-d H:i:s', time());

        return Owner::create($carOwnerData);
    }

    // 退车
    public function refund()
    {
        $car_id = I('post.car_id/d', 0);
        if ($car_id < 1) {
            $this->helpJsonResult(400, "车辆编号参数错误");
        }
        $order_id = I('post.order_id/d', 0);
        if ($order_id < 1) {
            $this->helpJsonResult(400, "拍单号参数错误");
        }
        $owner_id = I('post.owner_id/d', 0);
        $bc_id = I('post.bc_id/d', 0);
        if ($bc_id < 1) {
            $this->helpJsonResult(400, "车主编号参数错误");
        }
        $bc = new BreachCar($car_id);
        $bc_info = $bc->iss_detail($bc_id);
        if (empty($bc_info)) {
            $this->helpJsonResult(400, "未查询到违约车辆信息");
        }
        $remark = I('post.refund_remark');
        if (empty($remark)) {
            $this->helpJsonResult(400, "请输入退车原因");
        }
        $compensate = I('post.compensate');
        if ($compensate < 0) {
            $this->helpJsonResult(400, "金额不能为空");
        }

        $back_method = I('post.back_method', 0);
        $account_id = I('post.account_id');
        $bank_name = I('post.bank_name');
        $card_no = I('post.card_no');
        $account_name = I('post.account_name');
        $paymentReason = I('post.payment_reason');
        $now = date("Y-m-d H:i:s");
        $car = new Car($car_id);
        $car_info = $car->detail();
        $carReport = new CarReportLogic($car_id);
        $branchId = $carReport->getBranchId();

        //$order_id = $car->get_orderid_by_carid($car_id);
        $mid = $bc_info['mid'];

        $breachData = [
            'status' => 2,
            'compensate' => $compensate,
            'remark' => $remark,
            'back_method' => $back_method,
            'back_reason' => $paymentReason,
            'emp_id' => $this->user_info['emp_id'],
            'emp_name' => $this->user_info['real_name'],
            'deal_time' => $now,
        ];

        //开启事务
        M()->startTrans();
        $refundCarData = []; //退车信息
        $refundCarData['compensate'] = $compensate; // 赔付/扣除 金额
        //if (!empty($mid)) { //如果变更单号，不为空。就表示新的数据。走新的退车流程
        $paymentAmount = I('post.payment_amount');
        $remarkAmountOfCar = I('post.remark_amount_of_car');
        $remarkPayment = I('post.remark_payment');

        $refundCarData['payment_amount'] = $paymentAmount;//付款金额
        $refundCarData['remark_amount_of_car'] = $remarkAmountOfCar; //车款备注
        $refundCarData['remark_payment'] = $remarkPayment; //付款备注
        $accountData = [];
        if ($car_info['car_source'] == 1) { //如果是4s店车源，直接使用传过来的账号信息
            $accountData['card_no'] = $card_no;
            $accountData['bank_name'] = $bank_name;
            $accountData['account_name'] = $account_name;

        } elseif ($car_info['car_source'] == 2) //如果是个人车源，就从签约表中，查询相应的账号信息
        {
            $signatureObj = new Signature();
            $signatureData = $signatureObj->getDetailByOrderId($order_id);

            $accountData['card_no'] = $signatureData['payee_account'];
            $accountData['bank_name'] = $signatureData['deposit_bank'];
            $accountData['account_name'] = $signatureData['payee_name'];
        }

        if ($paymentReason == 1) { //平台失误
            $lastRefundCarData = $this->platformError($car_info['sid'], $paymentAmount, $order_id, $refundCarData, $accountData, $branchId);
        } elseif ($paymentReason == 2) { //卖方违约
            $lastRefundCarData = $this->ownerBreach($car_info['sid'], $paymentAmount, $order_id, $refundCarData, $branchId);
        } else { //平退
            $lastRefundCarData = $this->normalRefund($car_info['sid'], $order_id, $refundCarData, $branchId);
        }

        $lastData = [];
        $lastData['order_id'] = $order_id;
        $lastData['mid'] = $mid;
        $lastData['is_dealer'] = 2;//车主
        $last_change_info = ChangeOrder::getLastChangeOrder($lastData);
        if ($last_change_info) {
            $res_void_last_change = ChangeOrder::voidLastChange($last_change_info['mid'], '');
            if (!$res_void_last_change) {
                M()->rollback();
                $this->helpJsonResult(500, "作废赔付车主付款单失败!");
            }
        }

        $carData = [
            'car_status' => 8,  //交易失败
            'fail_type' => 2, //失败类型 1 车主不卖  2 退车
            'modify_time' => date('Y-m-d H:i:s', time()),
        ];

        $breachRes = $bc->update($breachData, $bc_id);
        if (!$breachRes) {
            M()->rollback();
            $this->helpJsonResult(500, "更新违约表失败");
        }

        $lastRefundCarData['order_id'] = $order_id;
        $lastRefundCarData['car_id'] = $car_id;
        $lastRefundCarData['sid'] = $car_info['sid'];
        $lastRefundCarData['refer_id'] = $bc_id;
        $lastRefundCarData['create_time'] = date('Y-m-d H:i:s', time());
        $lastRefundCarData['type'] = 1; //1 违约车辆 2 自收车辆
        unset($lastRefundCarData['payment_amount']);
        $result = RefundLogic::add($lastRefundCarData);
        if (!$result) {
            M()->rollback();
            $this->helpJsonResult(422, '添加退车信息失败');
        }

        $carRes = $car->update($carData);
        if (!$carRes) {
            M()->rollback();
            $this->helpJsonResult(500, "更新车源表失败");
        }
        M()->commit();
        // } else {
        /* $breachRes = $bc->update($breachData, $bc_id);

         if (!$breachRes) {
             M()->rollback();
             Log::record("车商违约退车,更新违约信息失败。car_id: {$car_id}", "ERR", true);
             $this->helpJsonResult(500, "操作失败");
         }
         //添加打款帐号
         if ($car_info['car_source'] == 1 && $car_info['pay_status'] < 2) {
             $bank_account = json_encode(
                 [
                     'bank_name' => $bank_name,
                     'card_no' => $card_no,
                     'account_name' => $account_name
                 ], JSON_UNESCAPED_UNICODE
             );
             $bc_update_data['fid'] = $account_id;
             $bc_update_data['bank_account'] = $bank_account;
             $rs = $bc->update($bc_update_data, $bc_id);
             if (!$rs) {
                 M()->rollback();
                 $this->helpJsonResult(500, "操作失败");
             }
         }

         if ($car_info['pay_status'] < 2) {
             $carData = [
                 'car_status' => 8,  //交易失败
                 'fail_type' => 2,
                 'pay_status' => -1,
                 'modify_time' => date('Y-m-d H:i:s', time()),
             ];
         } else {
             $carData = [
                 'car_status' => 8,  //交易失败
                 'fail_type' => 2,
                 'modify_time' => date('Y-m-d H:i:s', time()),
             ];
         }
         $carRes = $car->update($carData);
         if (!$carRes) {
             M()->rollback();
             Log::record("车商违约退车,更新车辆信息失败。car_id: {$car_id}", "ERR", true);
             $this->helpJsonResult(500, "操作失败");
         }
         $is_pay = array(
             'owner_id' => $owner_id,
             'order_id' => $order_id,
             'car_id' => $car_id,
             'emp_id' => $this->emp_id,
             'back_method' => $back_method,
             'pay_status' => $car_info['pay_status'],
             'three_in_one' => $car_info['three_in_one'],
             'car_source' => $car_info['car_source'],
             'compensate_type' => $bc_info['compensate_type'],
             'compensate' => $compensate
         );
         $rs2 = $bc->is_compensate_Pay($is_pay);
         if (!$rs2) {
             M()->rollback();
             $this->helpJsonResult(500, "操作失败");
         }
         //更改车源状态
         $CarSource = new CarSource($car_info['sid']);
         $csData = [];
         $csData['status'] = 600;
         $res_cs = $CarSource->update($csData);

         M()->commit();
         if ($car_info['pay_status'] > 0) {
             $pay_map = array();
             $pay_map['car_id'] = array('eq', $car_id);
             $pay_map['status'] = array('eq', 0);
             $data = array();
             $data['status'] = 2;
             M('pay_log')->where($pay_map)->save($data);
         }*/
        //}
        $this->log_record($car_id, $order_id, '违约车辆，退车');
        $this->helpJsonResult(200, 'success');
    }


    /**
     *
     * 平台失误
     *
     * @param int $sid 车源编号
     * @param int $paymentAmount 赔付金额
     * @param int $order_id 拍单编号
     * @param array $breachData 违约车辆数据
     * @param array $accountData 账号信息
     * @param int $branchId 分公司编号
     * @return mixed
     */
    public function platformError($sid, $paymentAmount, $order_id, $breachData, $accountData, $branchId)
    {
        $purchaseOrderObj = new PurchaseOrder();
        $purchaseOrderData = $purchaseOrderObj->viewBySid($sid);
        if (empty($purchaseOrderData)) {
            $this->helpJsonResult('500', '采购单数据有误!');
            return false;
        }
        $purchaseOrderId = $purchaseOrderData['id']; //采购单编号
        $result = $purchaseOrderObj->closeById($purchaseOrderId); //关闭采购单
        if (!$result) {
            M()->rollback();
            $this->helpJsonResult('500', '关闭采购单失败');
        }

        $paymentRelation = $purchaseOrderObj->getPaymentAndPurchaseOrderRelation($purchaseOrderId, [1, 2]);
        $paymentId = $paymentRelation['payment_id'];

        $paymentObj = new Payment($paymentId);
        $paymentData = $paymentObj->getInfo();

        $breachData['compensate'] = $paymentAmount; //赔付金额
        $breachData['back_reason'] = 1; // 退车原因 1 平台失误，2 卖方违约 3 平退
        if (!$paymentData) { //如果没有付款单（个人车源，三证不合一的没有首付款单）
            $paymentStatus = 0; //设置状态为0
        } else {
            $paymentStatus = $paymentData['status'];
        }

        if ($paymentStatus == 2 || $paymentStatus == 0) { //如果是未付或者锁定状态,就作废原来的付款单。赔付平台违约金
            ///$amountPaid = '0'; //已付金额等于0
            //$amount = $paymentData['amount']; //原来的付款金额
            $lastAmount = $paymentAmount; //赔付金额 = 这次要赔付金额
            if ($paymentData) { //如果存在付款单，就作废
                $oldPaymentData['status'] = 3; //作废原来的未付款单
                $result = $paymentObj->update($oldPaymentData);
                if ($result === false) {
                    M()->rollback();
                    $this->helpJsonResult('500', '作废首付款单失败');
                    return false;
                }
            }

            if ($lastAmount > 0) { //当输入的金额大于0 时，才生成付款单
                $data['pay_type'] = 6;
                $data['pay_way'] = 2;
                $data['amount'] = $lastAmount;
                $data['create_time'] = date('Y-m-d H:i:s', time());
                $data['bank_name'] = $accountData['bank_name'];
                $data['account_name'] = $accountData['account_name'];
                $data['card_no'] = $accountData['card_no'];
                $data['refer'] = 1; //来源于违约车辆
                $data['branch_id'] = $branchId; //分公司编号

                $paymentId = Payment::add($data); //6,代表赔付车主的钱
                $result = $purchaseOrderObj->addPaymentAndPurchaseOrderRelation($purchaseOrderId, $paymentId, '6');//6 代表 赔付车主
                if ($result === false) {
                    M()->rollback();
                    $this->helpJsonResult('500', '添加付款单和采购单关系失败');
                    return false;
                }
                $breachData['payment_id'] = $paymentId; //付款单号
            }
        } elseif ($paymentStatus == 1) { //如果已付状态
            $amount = $paymentData['amount']; //原来的付款金额
            $lastAmount = $amount - $paymentAmount; //最后的金额 = 原来的付款金额 - 这次赔付金额
            if ($lastAmount > 0) { //生成收款单
                $data = [
                    'payment_type' => '7',
                    'payment_method' => '1',
                    'amount' => $lastAmount,
                    'refer' => 1, //来源于违约车辆
                    'create_time' => date('Y-m-d H:i:s', time()),
                    'branch_id' => $branchId, //分公司编号
                ];
                $collectionId = Collection::add($data);
                if ($collectionId === false) {
                    M()->rollback();
                    $this->helpJsonResult('500', '添加收款单失败');
                    return false;
                }
                $auOrderObj = new AuOrder($order_id);
                $result = $auOrderObj->addCollectionAndOrderRelation($order_id, $collectionId, '7'); //7 应收车主
                if ($result === false) {
                    M()->rollback();
                    $this->helpJsonResult('500', '添加收款单失败');
                    return false;
                }

                $breachData['collection_id_car'] = $collectionId; //收款单号


            } elseif ($lastAmount < 0) { //生成付款单
                $data['pay_type'] = 6;
                $data['pay_way'] = 2;
                $data['amount'] = ($paymentAmount - $amount);
                $data['create_time'] = date('Y-m-d H:i:s', time());
                $data['bank_name'] = $paymentData['bank_name'];
                $data['account_name'] = $paymentData['account_name'];
                $data['card_no'] = $paymentData['card_no'];
                $data['refer'] = 1; //来源于违约车辆
                $data['branch_id'] = $branchId; //分公司编号

                $paymentId = Payment::add($data);
                $result = $purchaseOrderObj->addPaymentAndPurchaseOrderRelation($purchaseOrderId, $paymentId, '6');//6 代表 赔付车主
                if ($result === false) {
                    M()->rollback();
                    $this->helpJsonResult('500', '添加付款单，采购单关系失败');
                    return false;
                }
                $breachData['payment_id'] = $paymentId; //付款单号
            }
        } elseif ($paymentStatus == 3) {
            M()->rollback();
            $this->helpJsonResult(500, "付款单信息有误");
            return false;
        }
        //print_r($breachData);return;
        return $breachData;
    }

    /**
     * 卖方违约
     *
     * @param int $sid 车源编号
     * @param int $paymentAmount 赔付金额
     * @param int $order_id 拍单编号
     * @param array $breachData 违约车辆数据
     * @param  int $branchId 分公司编号
     * @return mixed
     */
    public function ownerBreach($sid, $paymentAmount, $order_id, $breachData, $branchId)
    {
        //根据sid，获取采购单
        $purchaseOrderObj = new PurchaseOrder();
        $purchaseOrderData = $purchaseOrderObj->viewBySid($sid);
        if (empty($purchaseOrderData)) {
            M()->rollback();
            $this->helpJsonResult('500', '采购单数据有误!');
            return false;
        }
        $purchaseOrderId = $purchaseOrderData['id']; //采购单编号
        $result = $purchaseOrderObj->closeById($purchaseOrderId); //关闭采购单
        if ($result === false) {
            M()->rollback();
            $this->helpJsonResult('500', '关闭采购单失败');
            return false;
        }

        //根据采购单编号和付款单类型，获取相应的付款单
        $paymentRelation = $purchaseOrderObj->getPaymentAndPurchaseOrderRelation($purchaseOrderId, [1, 2]);
        $paymentId = $paymentRelation['payment_id'];

        $paymentObj = new Payment($paymentId);
        $paymentData = $paymentObj->getInfo();
        if (!$paymentData) { //如果没有付款单（个人车源，三证不合一的没有首付款单）
            $paymentStatus = 0; //设置状态为0
        } else {
            $paymentStatus = $paymentData['status'];
        }
        $breachData['compensate'] = $paymentAmount; //赔付金额
        $breachData['back_reason'] = 2; // 退车原因 1 平台失误，2 卖方违约 3 平退

        if ($paymentStatus == 2 || $paymentStatus == 0) { //如果是未付或者锁定状态,就直接生成收款单
            if ($paymentData) { //如果存在付款单，就作废
                $oldPaemntData['status'] = 3; //作废原来的未付款单
                $result = $paymentObj->update($oldPaemntData);
                if ($result === false) {
                    M()->rollback();
                    $this->helpJsonResult('500', '作废首付款单失败');
                    return false;
                }
            }

            if ($paymentAmount > 0) { //生成违约金收款单
                $data = [
                    'payment_type' => '8',
                    'payment_method' => '1',
                    'amount' => $paymentAmount,
                    'refer' => 1, //来源于违约车辆
                    'create_time' => date('Y-m-d H:i:s', time()),
                    'branch_id' => $branchId, //分公司编号
                ];
                $result = $collectionId = Collection::add($data);
                if ($result === false) {
                    M()->rollback();
                    $this->helpJsonResult('500', '添加收款单失败');
                    return false;
                }

                $auOrderObj = new AuOrder($order_id);
                $result = $auOrderObj->addCollectionAndOrderRelation($order_id, $collectionId, '7'); //7 因收车主
                if ($result === false) {
                    M()->rollback();
                    $this->helpJsonResult('500', '添加收款单，拍单关系失败');
                    return false;
                }
                $breachData['collection_id'] = $collectionId; //收款单号
            }
        } elseif ($paymentStatus == 1) { //如果已付状态，就要收回首付款及赔付金额。此时生成两笔收款单一笔收回首付款，一笔收回卖方的赔付
            $amount = $paymentData['amount']; //原来的付款金额

            if ($amount > 0) { //生成 车款（首付款） 收款单
                $data = [
                    'payment_type' => '7', // 应收车主
                    'payment_method' => '1',
                    'amount' => $amount,
                    'refer' => 1, //来源于违约车辆
                    'create_time' => date('Y-m-d H:i:s', time()),
                    'branch_id' => $branchId, //分公司编号
                ];
                $result = $collectionId = Collection::add($data);
                if ($result === false) {
                    M()->rollback();
                    $this->helpJsonResult('500', '添加收款单失败');
                    return false;
                }
                $auOrderObj = new AuOrder($order_id);
                $result = $auOrderObj->addCollectionAndOrderRelation($order_id, $collectionId, '7'); //7 因收车主
                if ($result === false) {
                    M()->rollback();
                    $this->helpJsonResult('500', '添加收款单，拍单关系失败');
                    return false;
                }
                $breachData['collection_id_car'] = $collectionId; //车款收款单号
            }

            if ($paymentAmount > 0) { //生成 赔付 收款单
                $data = [
                    'payment_type' => '8', //8 车主违约金扣除
                    'payment_method' => '1',
                    'amount' => $paymentAmount,
                    'refer' => 1, //来源于违约车辆
                    'create_time' => date('Y-m-d H:i:s', time()),
                    'branch_id' => $branchId, //分公司编号
                ];
                $result = $collectionId = Collection::add($data);
                if ($result === false) {
                    M()->rollback();
                    $this->helpJsonResult('500', '添加收款单失败');
                    return false;
                }
                $auOrderObj = new AuOrder($order_id);
                $result = $auOrderObj->addCollectionAndOrderRelation($order_id, $collectionId, '8'); //7 因收车主
                if ($result === false) {
                    M()->rollback();
                    $this->helpJsonResult('500', '添加收款单，拍单关系失败');
                    return false;
                }
                $breachData['collection_id'] = $collectionId; //收款单号
            }
        } elseif ($paymentStatus == 3) {
            M()->rollback();
            $this->helpJsonResult(500, "付款单信息有误");
            return false;
        }
        return $breachData;
    }

    /**
     * 正常退款（平退）
     *
     * @param int $sid 车源编号
     * @param int $order_id 拍单号
     * @param array $breachData 违约车辆数据
     * @param int $branchId 分公司编号
     * @return mixed
     */
    public function normalRefund($sid, $order_id, $breachData, $branchId)
    {
        //TODO 根据sid，获取采购单
        $purchaseOrderObj = new PurchaseOrder();
        $purchaseOrderData = $purchaseOrderObj->viewBySid($sid);
        if (empty($purchaseOrderData)) {
            M()->rollback();
            $this->helpJsonResult('500', '采购单数据有误!');
            return false;
        }
        $purchaseOrderId = $purchaseOrderData['id']; //采购单编号
        $result = $purchaseOrderObj->closeById($purchaseOrderId); //关闭采购单
        if ($result === false) {
            M()->rollback();
            $this->helpJsonResult(500, "关闭采购单失败");
            return false;
        }
        //TODO 根据采购单编号和付款单类型，获取相应的付款单
        $paymentRelation = $purchaseOrderObj->getPaymentAndPurchaseOrderRelation($purchaseOrderId, [1, 2]);
        $paymentId = $paymentRelation['payment_id'];

        $paymentObj = new Payment($paymentId);
        $paymentData = $paymentObj->getInfo();

        if (!$paymentData) { //如果没有付款单（个人车源，三证不合一的没有首付款单）
            $paymentStatus = 0; //设置状态为0
        } else {
            $paymentStatus = $paymentData['status'];
        }
        $breachData['back_reason'] = 3; // 退车原因 1 平台失误，2 卖方违约 3 平退
        if ($paymentStatus == 1) { //如果已付状态
            $amount = $paymentData['amount']; //原来的付款金额

            if ($amount > 0) { //生成收款单
                $data = [
                    'payment_type' => '7',
                    'payment_method' => '1',
                    'amount' => $amount,
                    'refer' => 1, //来源于违约车辆
                    'create_time' => date('Y-m-d H:i:s', time()),
                    'branch_id' => $branchId, //分公司编号
                ];
                $result = $collectionId = Collection::add($data);
                if ($result === false) {
                    M()->rollback();
                    $this->helpJsonResult(500, "添加收款单失败");
                }
                $auOrderObj = new AuOrder($order_id);
                $result = $auOrderObj->addCollectionAndOrderRelation($order_id, $collectionId, '7'); //7 应收车主
                if ($result === false) {
                    M()->rollback();
                    $this->helpJsonResult(500, "添加收款单拍单关系失败");
                }
                $breachData['collection_id_car'] = $collectionId; //收款单号
            }
        } elseif ($paymentStatus == 0 || $paymentStatus == 2) { //如果未付或者是锁定状态
            if ($paymentData) { //如果付款单存在，就要作废未付款的付款单
                $data['status'] = 3; //作废原来的未付款单
                $result = $paymentObj->update($data);
                if ($result === false) {
                    M()->rollback();
                    $this->helpJsonResult('500', '作废付款单失败');
                    return false;
                }
            }
        } elseif ($paymentStatus == 3) {
            M()->rollback();
            $this->helpJsonResult(500, "付款单信息有误");
        }
        return $breachData;
    }

    //其他渠道成交
    public function other_channel_deal()
    {
        $car_id = I('post.car_id/d', 0);
        if ($car_id < 1) {
            $this->helpJsonResult(400, "参数错误");
        }
        $bc_id = I('post.bc_id/d', 0);
        if ($bc_id < 1) {
            $this->helpJsonResult(400, "参数错误");
        }
        $bc = new BreachCar($car_id);
        $bc_info = $bc->iss_detail($bc_id);
        if (empty($bc_info)) {
            $this->helpJsonResult(400, "未查询到违约车辆信息");
        }
        $trade_price = I('post.trade_price');
        if ($trade_price <= 0) {
            $this->helpJsonResult(400, "请输入正确的成交价");
        }

        $transfer_fee = I('post.transfer_fee');
        if ($transfer_fee < 0) {
            $this->helpJsonResult(400, "请输入正确的交付服务费");
        }

        $dealer_name = I('post.dealer');
        if (empty($dealer_name)) {
            $this->helpJsonResult(400, "请输入车商联系人");
        }
        $dealer_phone = I('post.dealer_phone');
        if (empty($dealer_phone)) {
            $this->helpJsonResult(400, "请输入车商联系人电话");
        }
        $take_car_man = I('post.take_car_man');
        if (empty($take_car_man)) {
            $this->helpJsonResult(400, "请输入提车人");
        }
        $remark = I('post.remark');

        $now = date("Y-m-d H:i:s");
        $car = new Car($car_id);
        $carReport = new CarReportLogic($car_id);
        $branchId = $carReport->getBranchId();

        M()->startTrans();
        $order_id = $car->get_orderid_by_carid($car_id);
        $auOrderObj = new AuOrder($order_id);
        $orderDetail = $auOrderObj->detail();
        //$orderNumber = $auOrderObj->createOrderNumber(1);//生成订单号

        //根据拍单编号更新拍单信息，是其他渠道成交。表示新生成的订单
        $orderNumber = gen_order_no(); //生成拍单号
        unset($orderDetail['order_id']);
        $orderDetail['order_no'] = $orderNumber;
        $orderDetail['emp_id'] = $this->emp_id;
        $orderDetail['car_id'] = $car_id;
        $orderDetail['transfer_fee'] = $transfer_fee;
        $orderDetail['success_price'] = $trade_price;
        $orderDetail['is_lock'] = 0;
        $orderDetail['is_other_channel_deal'] = 1; //是否其他渠道提交
        $orderDetail['dealer_pay_status'] = 1; // 车商付款状态 改为未付款
        $orderDetail['last_time'] = date('Y-m-d H:i:s', time());//最后修改时间
        $orderDetail['create_time'] = date('Y-m-d H:i:s', time());//创建时间
        $orderDetail['status'] = 8; //已签约
        $orderDetail['return_check_status'] = 7;//回车复检状态，协商成功
        $orderDetail['check_car_status'] = 3; //验车状态，改为验车成功
        $orderDetail['is_owner_issue'] = 0; //车主不存在争议
        $orderDetail['is_dealer_issue'] = 0; //车商不存在争议
        $orderDetail['dealer_issue_status'] = 2; //协商成功
        $orderDetail['is_other_channel_deal'] = 1;// 其他渠道成交
        $orderDetail['refer'] = 1; //来源 1 违约车辆

        $newOrderId = AuOrder::add($orderDetail);
        //echo M()->getLastSql();die();
        if ($newOrderId < 0) {
            M()->rollback();
            Log::record("违约车辆，其他渠道成交，新增拍单失败");
            $this->helpJsonResult(500, '操作失败', "新增拍单失败");
        }
        //新增order_fee
        $orderFeeData = [
            'success_price' => $trade_price,
            'transfer_fee' => $transfer_fee,
            'final_price' => $trade_price + $transfer_fee,
        ];
        $newOrder = new AuOrder($newOrderId);
        $resFee = $newOrder->addOrderFee($orderFeeData);
        if ($resFee < 0) {
            M()->rollback();
            Log::record("违约车辆，其他渠道成交，新增拍单费用失败，order_id: {$resFee} ");
            $this->helpJsonResult(500, '操作失败', "新增拍单费用失败");
        }

        //车辆信息
        $carData = [
            // 'car_status' => 9,
            'deal_type' => 1,
            'is_dealer_breach' => 1
        ];
        /*   if ($car_info['car_source'] == 1)
               $carData['pay_status'] = 2;*/
        $rsCar = $car->update($carData);
        if (!$rsCar) {
            M()->rollback();
            Log::record("违约车辆，其他渠道成交，更新车辆信息失败，car_id: {$car_id} ");
            $this->helpJsonResult(500, '操作失败', "更新车辆信息失败");
        }
       //创建收款单
        $collectionData = [
            'payment_type' => '1',
            'payment_method' => '1',
            'amount' => $trade_price + $transfer_fee,
            'emp_id' => $this->emp_id,
            'emp_name' => $this->user_info['real_name'],
            'create_time' => date('Y-m-d H:i:s', time()),
            'branch_id' => $branchId,
            'refer' => 1,
        ];
        $resCollection = $this->createCollection($collectionData, $newOrderId);
        if (!$resCollection) {
            M()->rollback();
            Log::record("违约车辆，其他渠道成交，新增收款单失败，car_id: {$car_id} ");
            $this->helpJsonResult(500, '操作失败', "新增收款单失败");
        }
        //更新违约车辆信息
        $breachCarData = [
            'status' => 3,
            'trade_price' => $trade_price,
            'transfer_fee' => $transfer_fee,
            'dealer_name' => $dealer_name,
            'dealer_phone' => $dealer_phone,
            'take_car_man' => $take_car_man,
            'emp_id' => $this->emp_id,
            'emp_name' => $this->user_info['real_name'],
            'remark' => $remark,
            'deal_time' => $now,
            'collection_id_car' => $resCollection,
            'd_order_id' => $newOrderId, //订单号
        ];
        $resBreachCar = $bc->update($breachCarData, $bc_id);
        if (!$resBreachCar) {
            M()->rollback();
            Log::record("违约车辆，其他渠道成交，更新违约车辆失败，car_id: {$car_id} ");
            $this->helpJsonResult(500, '操作失败', "更新违约车辆失败");
        }
        $unLockResult = $this->unLockAll($car);//解锁采购单及付款单
        if (!$unLockResult) {
            M()->rollback();
            Log::record("违约车辆，其他渠道成交，解锁采购单及付款单失败，car_id: {$car_id} ");
            $this->helpJsonResult(500, '操作失败', "解锁采购单及付款单失败");
        }
        M()->commit();
        $this->log_record($car_id, $newOrderId, '违约车辆，其他渠道成交');
        $this->helpJsonResult(200, 'success');
    }


    /**
     * 创建收款单
     *
     * @param  array $collectionData 收款单信息
     * @param int $orderId 拍单编号
     * @return bool 返回 false/收款单号
     */
    public function createCollection($collectionData, $orderId)
    {
        $collectionId = Collection::add($collectionData);
        if ($collectionId === false) {
            return false;
        }

        $orderObj = new AuOrder($orderId);
        $result = $orderObj->addCollectionAndOrderRelation($orderId, $collectionId, '1');//收款类型等于1，表示车款应收
        if ($result === false) {
            return false;
        }
        return $collectionId;
    }

    /**
     * 更新订单表，设置是否其他渠道提交为真
     *
     * @param $orderId
     * @return bool
     */
    public function updateOrder($orderId)
    {
        $orderObj = new AuOrder($orderId);
        $data = [
            'is_other_channel_deal' => 1,
        ];
        $result = $orderObj->update($data);
        return $result;
    }


    //记录日志信息
    private function log_record($car_id, $order_id, $action)
    {
        //记录员工操作日志
        $log = [
            'emp_id' => $this->emp_id,
            'order_id' => $order_id,
            'car_id' => $car_id,
            'owner_id' => 0,
            'action' => $action
        ];
        \AuctionCore\System\SystemLog::add($log);

        /**
         * 记录车辆跟踪日志
         */
        $car_action_data = array(
            'action_name' => $action,
            'emp_id' => $this->emp_id
        );
        \AuctionCore\CarResource\Car::add_car_trace_log($car_id, $car_action_data);

        /*记录拍品跟踪日志*/
        $order_action_data = array(
            'action_name' => $action,
            'emp_id' => $this->emp_id
        );
        AuOrder::add_order_trace_log($order_id, $order_action_data);
    }

}